package com.dfxy.blog.window;

import com.dfxy.blog.dao.ApproveDao;
import com.dfxy.blog.dao.BlogDao;
import com.dfxy.blog.entity.Blog;
import com.dfxy.blog.listener.PublishActionListener;
import com.dfxy.blog.panel.BlogPanel;
import com.dfxy.blog.util.DBUtil;
import com.mysql.cj.util.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class MainWindow extends JFrame {

    private String userName = "dfxy";
    private JLabel labelHello = new JLabel();
    // JTextField 单行文本输入框
    // JTextArea 多行文本输入框
    private JTextArea textAreaPublish = new JTextArea();
    private JButton buttonPublish = new JButton("发布");
    private JPanel panelBlogs = new JPanel();
    private JPanel panelTurnPage = new JPanel();
    private JButton buttonLastPage = new JButton("上一页");
    private JButton buttonNextPage = new JButton("下一页");
    private JCheckBox checkboxMine = new JCheckBox("只看我的");
    private JButton buttonMessage = new JButton("!");
    private Connection con;
    private BlogDao blogDao;
    private ApproveDao approveDao;
    private java.util.List<Blog> blogList;
    private java.util.List<Blog> myBlogList;
    private int globalPageNo;
    private int pageCount;
    private static final int PAGE_SIZE = 5;
    private boolean publishInitStatus = true;
    private String lastLogInTime;
    private java.util.List<Blog> newBlogList = new ArrayList<>();

    private Set<Integer> approveIdSet;

    public MainWindow () throws SQLException, ClassNotFoundException {
        init();
    }

    public MainWindow (String userName, String lastLogInTime) throws SQLException, ClassNotFoundException {
        this.userName = userName;
        this.lastLogInTime = lastLogInTime;
        init();
    }

    private void init() throws SQLException, ClassNotFoundException {
        this.setSize(800, 1000);

        con = DBUtil.getConnection();
        blogDao = new BlogDao();
        approveDao = new ApproveDao();

        Container container = this.getContentPane();
        container.setLayout(null);

        System.out.println(userName);
        labelHello.setText("欢迎回来，" + userName);
        labelHello.setBounds(50, 50, 100, 20);
        labelHello.setFont(new Font("楷体", Font.PLAIN, 16));
        container.add(labelHello);

        buttonMessage.setFont(new Font("黑体", Font.BOLD, 16));
        buttonMessage.setForeground(Color.RED);
        buttonMessage.setBounds(650, 20, 50, 50);

        buttonMessage.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!newBlogList.isEmpty()) {

                    Set<String> publisherNameSet = new HashSet<>();
                    for (Blog blog:newBlogList) {
                        String publisherName = blog.getUsername();
                        publisherNameSet.add(publisherName);
                    }

                    // ""  add 小红   "小红"
                    // "小红"  add 小刚  "小红,小刚"
                    // a += b             a = a + b
                    // publisherNameString += "," + publisherName;
                    // publisherNameString = publisherNameString + "," + publisherName;

                    String publisherNameString = "";
                    for (String publisherName:publisherNameSet) {
                        if (StringUtils.isEmptyOrWhitespaceOnly(publisherNameString)) {
                            publisherNameString = publisherName;
                        } else {
                            publisherNameString += "," + publisherName;
                        }
                    }

                    JOptionPane.showMessageDialog(
                            container,
                            "您上次离开后" + publisherNameString +"共发布了" + newBlogList.size() + "条新内容"
                    );
                }

                buttonMessage.setVisible(false);
            }
        });

        container.add(buttonMessage);

        publishInit();

        textAreaPublish.setBounds(50, 80, 650, 100);
        container.add(textAreaPublish);

        buttonPublish.setBounds(600, 180, 100, 40);

        buttonPublish.addActionListener(new PublishActionListener(
                textAreaPublish,
                userName,
                con,
                new BlogDao(),
                container,
                this
        ));

        container.add(buttonPublish);

        checkboxMine.setBounds(50, 240, 100, 20);

        checkboxMine.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (checkboxMine.isSelected()) {
                    pageCount = (myBlogList.size() - 1) / PAGE_SIZE + 1;
                    globalPageNo = Math.min(globalPageNo, pageCount - 1);

                    turnPage(globalPageNo);
                } else {
                    pageCount = (blogList.size() - 1) / PAGE_SIZE + 1;
                    turnPage(globalPageNo);
                }
            }
        });

        container.add(checkboxMine);

        panelBlogs.setBounds(50, 260, 650, 600);
        panelBlogs.setBackground(Color.WHITE);

        panelBlogs.setLayout(new GridLayout(PAGE_SIZE + 1, 1));

        // 获取全部博客列表
        blogList = blogDao.blogList(con);
        // 获取“我的”博客列表
        refreshMyBlogList();

        // 获取上次登录后其他人发布的博客
        for (Blog blog:blogList) {
            if (blog == null
                    || blog.getUsername() == null
                    || blog.getPublishTime() == null
                    || lastLogInTime == null
            ) {
                continue;
            }

            if ( (!blog.getUsername().equals(this.userName))
                    && BlogDao.dateTimeFormat(blog.getPublishTime()).compareTo(lastLogInTime) > 0) {
                newBlogList.add(blog);
            }
        }

        // 获取点赞列表
        approveIdSet = approveDao.approveIdSet(con, userName);

        // 获取每条博客的点赞用户列表
        /*
        for (Blog blog:blogList) {
            blog.setApproveUsernameSet(approveDao.approveUsernameSet(con, blog.getId()));
        }
        */

        // 布局博客展示面板
        globalPageNo = 0;
        for (int i = 0; i < PAGE_SIZE && i < blogList.size(); i++) {

            Blog blog = blogList.get(i);

            String publisherName = blog.getUsername();
            String publishTime = BlogDao.dateTimeFormat(blog.getPublishTime());
            String blogContent = blog.getContent();

            // 创建blogPanel并展示
            BlogPanel blogPanel = new BlogPanel(userName, publisherName, blogContent, publishTime, this);
            blogPanel.setBlog(blog);
            blogPanel.setSize(650, 100);

            if (approveIdSet.contains(blog.getId())) {
                blogPanel.getButtonApprove().setEnabled(false);
            } else {
                blogPanel.getButtonCancelApprove().setEnabled(false);
            }

            panelBlogs.add(blogPanel);
        }

        // (6 - 1) / 5 + 1 = 2   2
        // (5 - 1) / 5 + 1 = 1   1
        // (4 - 1) / 5 + 1 = 1   1
        // 3 / 5 = 0   1
        // 2 / 5 = 0   1
        // (1 - 1) / 5 + 1 = 1   1
        pageCount = (blogList.size() - 1) / PAGE_SIZE + 1;

        buttonLastPage.setEnabled(false);
        buttonLastPage.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                globalPageNo--;
                turnPage(globalPageNo);
            }
        });

        buttonNextPage.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                globalPageNo++;
                turnPage(globalPageNo);
            }
        });

        panelTurnPage.add(buttonLastPage);
        panelTurnPage.add(buttonNextPage);

        panelBlogs.add(panelTurnPage);

        container.add(panelBlogs);

        System.out.println(newBlogList);

        if (newBlogList.isEmpty()) {
            buttonMessage.setVisible(false);
        }
    }

    private void turnPage(int pageNo) {

        int firstBlogIndex = pageNo * PAGE_SIZE;
        java.util.List<Blog> showBlogList = blogList;
        if (checkboxMine.isSelected()) {
            showBlogList = myBlogList;
        }

        for (int i = 0; i < PAGE_SIZE; i++) {

            BlogPanel blogPanel = (BlogPanel) panelBlogs.getComponent(i);

            int blogIndex = firstBlogIndex + i;
            if (blogIndex < showBlogList.size()) {
                Blog blog = showBlogList.get(blogIndex);

                String publisherName = blog.getUsername();
                String publishTime = BlogDao.dateTimeFormat(blog.getPublishTime());
                String blogContent = blog.getContent();

                blogPanel.update(publisherName, blogContent, publishTime);
                blogPanel.setBlog(blog, approveIdSet.contains(blog.getId()));
            } else {
                blogPanel.clear();
                blogPanel.setBlog(null);
            }
        }

        if (pageNo + 1 >= pageCount) {
            buttonNextPage.setEnabled(false);
        } else {
            buttonNextPage.setEnabled(true);
        }

        if (pageNo <= 0) {
            buttonLastPage.setEnabled(false);
        } else {
            buttonLastPage.setEnabled(true);
        }
    }

    public void updateBlogList(java.util.List<Blog> newBlogList) {
        this.blogList = newBlogList;
        refreshMyBlogList();
        pageCount = (blogList.size() - 1) / PAGE_SIZE + 1;
        if (checkboxMine.isSelected()) {
            pageCount = (myBlogList.size() - 1) / PAGE_SIZE + 1;
        }
        turnPage(globalPageNo);
    }

    public void publishInit() {
        textAreaPublish.setText("写下今天的心情吧…");
        textAreaPublish.setForeground(Color.BLUE);
        buttonPublish.setEnabled(false);
        publishInitStatus = true;

        textAreaPublish.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {

                if (publishInitStatus) {
                    textAreaPublish.setText("");
                    textAreaPublish.setForeground(Color.BLACK);
                    buttonPublish.setEnabled(true);
                    publishInitStatus = false;
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {

            }

            @Override
            public void mouseReleased(MouseEvent e) {

            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent e) {

            }
        });
    }

    private void refreshMyBlogList() {
        myBlogList = new ArrayList<Blog>();

        for (Blog blog:blogList) {
            System.out.println(this.userName + "\t" + blog.getUsername());
            if(blog != null
                    && blog.getUsername() != null
                    && blog.getUsername().equals(this.userName)
            ) {
                myBlogList.add(blog);
            }
        }
    }

    public void refreshApproveIdSet() throws SQLException, ClassNotFoundException {

        if (approveDao == null) {
            approveDao = new ApproveDao();
        }

        if (con == null) {
            con = DBUtil.getConnection();
        }

        approveIdSet = approveDao.approveIdSet(con, userName);
    }

    public static void main(String args[]) throws SQLException, ClassNotFoundException {
        MainWindow mainWindow = new MainWindow();
        mainWindow.setVisible(true);
    }
}
